from pyjvm import vmcnf
from pyjvm import vm
import os


def mk_class_path(cp):
    if not os.path.exists(cp):
        # noinspection PyBroadException
        try:
            os.makedirs(cp)
        except Exception as _:
            print('无法创建class目录：%s' % (cp))


def javac(class_name, src_dir, class_dir):
    name = class_name.replace('.', '/')
    java_file = os.path.join(src_dir, name + '.java')

    if os.path.isfile(java_file):
        klass = os.path.join(class_dir, name + '.class')
        cmd = 'javac %s -d %s -encoding UTF-8' % (java_file, class_dir)
        os.system(cmd)
        print(cmd)


java_dir = os.path.abspath('./java-proj-for-test/src/main/java/')
class_path = os.path.abspath('./java-proj-for-test/build/classes/java/main')
mk_class_path(class_path)
vmcnf.classpath.append(class_path)
# vmcnf.jre = '/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre'
py_jvm = vm.PyJvm(vmcnf)


def exec_main(class_name):
    javac(class_name, java_dir, class_path)
    py_jvm.exec_main(class_name, [])
